<?php

/*
	aterr - a threaded forum system.

	Copyright (c) 2006 Chris Jenkinson <chris@starglade.org>.
	All rights reserved.

	aterr is licensed under the GNU General Public License.
	<http://opensource.org/licenses/gpl-license.php>
*/

class template
{
	var $template_path;
	var $files = array();
	
	function template($file)
	{
		$this->template_path = INCLUDE_PATH . 'tpl/';
		
		$this->open_tpl_file($file);
	}
	
	function open_tpl_file($file)
	{
		if (function_exists('file_get_contents'))
		{
			$this->files[$file]['raw'] = @file_get_contents($this->template_path . $file) or die("Could not open $file.");
		}
		
		$f_array = @file($this->template_path . $file) or die("Could not open $file.");
		
		$this->files[$file]['raw'] = implode("", $f_array);
	}
	
	function parse($file)
	{
		$text = $this->files[$file]['raw'];
		
		foreach ($this->file[$file]['vars'] as $key => $value)
		{
			if (is_array($value))
			{	
				if (preg_match("/\[\[$key\]\](.*)\[\[\/$key\]\]/ms", $text, $matches))
				{
					$items = array();
					$tmp = $matches[1];
					
					foreach ($value as $item)
					{
						$tmp = $matches[1];
						
						foreach ($item as $item_key => $item_value)
						{
							$tmp = str_replace("[[$key.$item_key]]", $item_value, $tmp);
						}
						
						$items[] = $tmp;
					}
					
					$text = str_replace($matches[0], implode('', $items), $text);
				}
			}
			else
			{
				$text = str_replace("[[$key]]", $value, $text);
			}
		}
		
		$this->files[$file]['parsed'] = $text;
	}
	
	function add_vars($file, $array)
	{
		$this->file[$file]['vars'] = array_merge($this->file[$file]['vars'], $array);
	}
	
	function add_block_vars($file, $block, $array)
	{
		$this->file[$file]['vars'][$block][] = $array;
	}
	
	function output($file)
	{
		return $this->files[$file]['parsed'];
	}
}

?>
